#include "ClientHandler.h"
#include "global.h"
#include "EncryptDecrypt.h"
#include "TcpListener.h"
#include "wspack.h"


CClientHandler::CClientHandler()
{
	m_pListener = NULL;
	m_heat_beat_timer.SetTimeEventObj(this, HEART_BEATT_TIME_ID);
	this->m_HandlerID = 0;
}

CClientHandler::~CClientHandler()
{
	m_heat_beat_timer.StopTimer();
	m_pServer->m_handlerList.erase(m_HandlerID);
}

int CClientHandler::ProcessOnTimerOut(int Timerid)
{
	if (HEART_BEATT_TIME_ID == Timerid)
	{
		//StopTimer();
		//OnClose();
		//delete this;
		handle_close();
	}
	return 0;
}

int CClientHandler::OnConnected()
{
	if (NULL != m_pServer && m_pServer->IsHeatBeatCheck())
		m_heat_beat_timer.StartTimer2(HEART_BEATT_TIME_OUT);

	return 0;
}

int CClientHandler::OnClose() 
{
	if (NULL != m_pServer)
		return m_pServer->OnClose(this);

	return 0;	
}

ICC_Decoder*  CClientHandler::CreateDecoder()
{
	return new Decoder();
}

int CClientHandler::Send(CCPacketBase* pPacket)
{
	const char* buf = pPacket->packet_buf();
	unsigned int buflen = pPacket->packet_size();
	if (DATA_PROTOCOL_WEBSOCKET == getDataProtocol())
	{
		CWspack outwspack;
		outwspack.set_fin(0x01);
		outwspack.set_opcode(CWspack::WSOpcode_Binary);
		outwspack.pack_dataframe(pPacket->packet_buf(), pPacket->packet_size());
		buf = outwspack.data();
		buflen = outwspack.entire_data_len();
	}
	
    int ret = CCSocketHandler::Send(buf, buflen);

    return ret;
}

int CClientHandler::OnPacketComplete(const char * data, int len)
{
    NETInputPacket input;
    input.Copy(data,len);

	if (NULL != m_pServer && m_pServer->IsHeatBeatCheck())
		m_heat_beat_timer.StartTimer2(HEART_BEATT_TIME_OUT);

	if (HEART_BEATT_CMD == input.GetCmdType())
	{
		this->Send(&input);
		return 0;
	}

/*	uint32 bitflag = input.Getbitflag();
	if(bitflag&g_encodeflag)
	{
		CEncryptDecrypt::DecryptBuffer1(&input);
	}*/

    //log_debug("pack,bitflag:%d, bplen:%d", input.Getbitflag(), input.bodylen());
    int iret = -1;
	if (NULL != m_pServer)
		iret = m_pServer->ProcessPacket(this, &input);

    if(iret < 0)
	{
		log_error(" Process Packet[0x%x] Failed.",  input.GetCmdType());
    }
    return iret;
}

int CClientHandler::Init()
{
	CCSocketHandler::Init();
	return 0;
}

